package fun._6742.service.impl;


import cn.hutool.core.bean.BeanUtil;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import fun._6742.mapper.ProductOrderItemMapper;
import fun._6742.model.dataobject.ProductDO;
import fun._6742.model.dataobject.ProductOrderItemDO;
import fun._6742.model.valueobject.OrderItemVO;
import fun._6742.request.ConfirmOrderRequest;
import fun._6742.service.ProductOrderItemService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;

import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

/**
 * <p>
 * 服务实现类
 * </p>
 *
 * @author LiuQ
 * @since 2022-09-22
 */
@Slf4j
@Service
public class ProductOrderItemServiceImpl extends ServiceImpl<ProductOrderItemMapper, ProductOrderItemDO> implements ProductOrderItemService {

    @Override
    public List<OrderItemVO> listAllItems(long id) {
        List<ProductOrderItemDO> productOrderItemDOList = list(new QueryWrapper<ProductOrderItemDO>().eq("product_order_id", id));
        return productOrderItemDOList.stream().map(obj -> {
            OrderItemVO vo = new OrderItemVO();
            BeanUtil.copyProperties(obj, vo);
            return vo;
        }).collect(Collectors.toList());

    }
    @Override
    public void createOrderItem(Long orderId, ConfirmOrderRequest confirmOrderRequest, List<ProductDO> productDOList) {
        List<ProductOrderItemDO> productOrderItemDOList = new ArrayList<>();
        Map<Long, Integer> map = confirmOrderRequest.getProductIdAndNums();
        Date date = new Date();
        for (ProductDO productDO : productDOList) {
            productOrderItemDOList.add(ProductOrderItemDO
                    .builder()
                    .productOrderId(orderId)
                    .productId(productDO.getId())
                    .productName(productDO.getTitle())
                    .productImg(productDO.getCoverImg())
                    .buyNum(map.get(productDO.getId()))
                    .createTime(date)
                    .totalAmount(productDO.getPrice().multiply(new BigDecimal(map.get(productDO.getId()))))
                    .amount(productDO.getPrice())
                    .build());
        }
        saveBatch(productOrderItemDOList);
    }


}
